<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="方案名称" prop="solutionName">
        <el-input v-model="queryParams.solutionName" placeholder="请输入方案名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="方案状态" prop="solutionStatus">
        <el-select v-model="queryParams.solutionStatus" placeholder="请选择方案状态" clearable>
          <el-option v-for="dict in solution_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="方案分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择方案分类" clearable>
          <el-option v-for="item in cateGoryList" :key="item.id" :label="item.categoryName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['solution:solutions:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['solution:solutions:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['solution:solutions:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['solution:solutions:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="solutionsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="方案名称" align="center" prop="solutionName" />
      <el-table-column label="分类" align="center" prop="categoryID">
        <template #default="scope">
          {{ getCategoryNames(scope.row.categoryID) }}
        </template>
      </el-table-column>
      <el-table-column label="方案状态" align="center" prop="solutionStatus">
        <template #default="scope">
          <dict-tag :options="solution_status" :value="scope.row.solutionStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['solution:solutions:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['solution:solutions:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改方案管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="solutionsRef" :model="form" :rules="rules" label-width="100px" class="form">
        <el-form-item label="方案名称" prop="solutionName">
          <el-input v-model="form.solutionName" placeholder="请输入方案名称" class="input" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryID">
          <el-select v-model="form.categoryID" placeholder="请选择方案状态" multiple>
            <el-option v-for="item in cateGoryList" :key="item.id" :label="item.categoryName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方案状态" prop="solutionStatus" v-if="form.id !== null">
          <el-select v-model="form.solutionStatus" placeholder="请选择方案状态">
            <el-option v-for="dict in solution_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImageUrl">
          <image-upload v-model="form.coverImageUrl" />
        </el-form-item>
        <el-form-item label="视频" prop="videoUrl">
          <file-upload v-model="form.videoUrl" />
        </el-form-item>
        <el-form-item label="方案摘要" prop="summary">
          <el-input v-model="form.summary" type="textarea" autosize placeholder="请输入内容" class="textarea" />
        </el-form-item>
        <el-form-item label="方案详情">
          <editor v-model="form.details" :min-height="192" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Solutions">
import { listSolutions, getSolutions, delSolutions, addSolutions, updateSolutions } from "@/api/solution/solutions";
import { listCategories } from "@/api/solution/categories";
import { loadAllParams } from "@/api/page";
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';

const { proxy } = getCurrentInstance();
const { solution_status } = proxy.useDict('solution_status');

const solutionsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: null,
    solutionName: null,
    solutionStatus: null,
    coverImageUrl: null,
    videoUrl: null,
    summary: null,
    details: null,
    categoryID: [] // 确保 categoryID 是一个数组
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    solutionName: null,
    solutionStatus: [],
    categoryId: null
  },
  rules: {
    solutionName: [
      { required: true, message: "方案名称不能为空", trigger: "blur" },
      { min: 3, max: 20, message: "方案名称长度必须在 3 到 20 个字符之间", trigger: "blur" }
    ],
    categoryID: [
      {
        required: true, message: "方案分类不能为空", trigger: "blur"
      }
    ],
    solutionStatus: [
      { required: true, message: "方案状态不能为空", trigger: "change" }
    ],
    coverImageUrl: [
      { required: true, message: "方案封面图URL不能为空", trigger: "blur" }
    ],
    summary: [
      { required: true, message: "方案摘要不能为空", trigger: "blur" },
      { min: 50, max: 300, message: "方案摘要字符必须在 50 到 300 个字符之间", trigger: "blur" }

    ],
    details: [
      { required: true, message: "方案详情不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询方案管理列表 */
function getList() {
  loading.value = true;
  listSolutions(queryParams.value).then(response => {
    solutionsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    solutionName: null,
    solutionStatus: null,
    coverImageUrl: null,
    videoUrl: null,
    summary: null,
    details: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    categoryID: [] // 确保 categoryID 是一个数组
  };
  queryParams.value.solutionStatus = []; // 修改为数组
  proxy.resetForm("solutionsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加方案";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getSolutions(_id).then(response => {
    form.value = response.data;
    // 清理可能包含无效字符的数据
    for (const key in form.value) {
      console.log(1)
      console.log(typeof form.value[key] === 'string')
      if (typeof form.value[key] === 'string') {
        form.value[key] = form.value[key].replace(/"/g, '');
      }
    }
    open.value = true;
    title.value = "修改方案";
    console.log('Form Data:', form.value); // 调试信息
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["solutionsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSolutions(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSolutions(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除该方案？').then(function () {
    return delSolutions(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('solution/solutions/export', {
    ...queryParams.value
  }, `solutions_${new Date().getTime()}.xlsx`);
}

const cateGoryList = ref([]);

function getCategoryList() {
  loadAllParams.status = 1
  listCategories(loadAllParams).then(response => {
    cateGoryList.value = response.rows;
  });
}

/* 获取方案分类 */
function getCategoryNames(categoryIDs) {
  const name = categoryIDs.map(categoryID => {
    const category = cateGoryList.value.find(item => item.id === categoryID);
    return category ? category.categoryName : '未知分类';
  }).join(', ');
  return name;
}

getCategoryList();
getList();
</script>
<style lang="scss" scoped>
.form {
  .input {
    width: 300px;
  }

  .textarea {
    resize: none;
    /* 禁止调整大小 */
    width: 600px;

    :deep(.el-textarea__inner) {
      resize: none;

    }
  }
}
</style>